import { NextResponse, NextRequest } from 'next/server'
import db, { todoQueries, auditQueries, userQueries, createAuditLog, todoProjectLinkQueries } from '@/lib/database-prisma'
import { getUserFromRequest } from "@/lib/auth-utils"

interface RouteContext {
  params: Promise<{ todoId: string }>
}

export async function DELETE(request: NextRequest, context: RouteContext) {
  const currentUser = await getUserFromRequest(request);
  if (!currentUser || !currentUser.id) {
    return NextResponse.json({ message: '用户未认证或无法获取用户ID' }, { status: 401 });
  }
  const currentUserId = currentUser.id;

  // 等待 params
  const { todoId } = await context.params;
  const todoIdNum = parseInt(todoId, 10);
  if (isNaN(todoIdNum)) {
    return NextResponse.json({ message: '无效的TODO ID' }, { status: 400 });
  }

  try {
    const todoToDelete = await todoQueries.findById.get(todoIdNum);
    if (!todoToDelete) {
      return NextResponse.json({ message: 'TODO任务未找到' }, { status: 404 });
    }

    // 获取 project_id 用于审计日志
    const linkInfos = await todoProjectLinkQueries.getProjectsByTodoId.all(todoIdNum);
    const projectIdForAudit = linkInfos.length > 0 ? linkInfos[0].project_id : null;

    // 在删除之前先创建审计日志
    if (todoToDelete && todoToDelete.content) {
      await createAuditLog(
        currentUserId,
        {
          type: "todo",
          id: todoIdNum,
          user: currentUser.name,
          act: "delete",
          fieldsChanged: ["status"],
          oldValue: {
            content: todoToDelete.content,
            status: todoToDelete.status,
            tags: todoToDelete.tags,
            assigned_to: todoToDelete.assignedTo
          },
          time: new Date().toISOString(),
        },
        projectIdForAudit === null ? undefined : projectIdForAudit,
        todoIdNum
      );
    }

    // 然后删除TodoList
    await todoQueries.delete.run(todoIdNum);

    return NextResponse.json({ message: '任务删除成功' }, { status: 200 });

  } catch (error: any) {
    console.error(`删除TODO任务 ${todoIdNum} 失败:`, error);
    if (error.message.includes('任务删除失败或任务已被删除')) {
        return NextResponse.json({ message: error.message }, { status: 404 });
    }
    return NextResponse.json({ message: `服务器内部错误: ${error.message || '未知错误'}` }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, context: RouteContext) {
  const currentUser = await getUserFromRequest(request);
  if (!currentUser || !currentUser.id) {
    return NextResponse.json({ message: '用户未认证或无法获取用户ID' }, { status: 401 });
  }
  const currentUserId = currentUser.id;

  // 等待 params
  const { todoId } = await context.params;
  const todoIdNum = parseInt(todoId, 10);
  if (isNaN(todoIdNum)) {
    return NextResponse.json({ message: '无效的TODO ID' }, { status: 400 });
  }

  try {
    const body = await request.json();
    const { content, tags, assigned_to, status } = body;

    // Fields allowed to be updated
    if (!content && !tags && assigned_to === undefined && !status) {
      return NextResponse.json({ message: '请求体中至少需要一个待更新的字段 (content, tags, assigned_to, status)' }, { status: 400 });
    }

    const existingTodo = await todoQueries.findById.get(todoIdNum);
    if (!existingTodo) {
      return NextResponse.json({ message: 'TODO任务未找到' }, { status: 404 });
    }

    const finalContent = content !== undefined ? content : existingTodo.content;
    const tagsString = tags !== undefined 
        ? (Array.isArray(tags) && tags.length > 0 ? tags.join(',') : (tags === null || tags === '' ? null : existingTodo.tags)) 
        : existingTodo.tags;
    const finalAssignedTo = assigned_to !== undefined 
        ? (assigned_to === null ? null : Number(assigned_to)) 
        : existingTodo.assignedTo;
    const finalStatus = status !== undefined ? status : existingTodo.status;

    // 直接更新，不使用事务
    await todoQueries.update.run(
      finalContent,
      tagsString,
      finalAssignedTo,
      finalStatus,
      todoIdNum
    );

    // 获取更新后的数据
    const updatedTodoRaw = await todoQueries.findById.get(todoIdNum);
    if (!updatedTodoRaw) {
      return NextResponse.json({ message: '更新todo后无法查询到该todo' }, { status: 500 });
    }
    
    const creator = await userQueries.findById.get(updatedTodoRaw.createdBy);
    const assignee = updatedTodoRaw.assignedTo ? await userQueries.findById.get(updatedTodoRaw.assignedTo) : null;

    // 获取 project_id 用于审计日志
    const linkInfos = await todoProjectLinkQueries.getProjectsByTodoId.all(todoIdNum);
    const projectIdForAudit = linkInfos.length > 0 ? linkInfos[0].project_id : null;

    const updatedTodoFull = {
      ...updatedTodoRaw,
      creator_name: creator?.name,
      creator_color: creator?.color,
      assignee_name: assignee?.name,
      assignee_color: assignee?.color,
    };

    // 添加审计日志（异步执行，不阻塞响应）
    createAuditLog(
      currentUserId,
      {
        type: "todo",
        id: todoIdNum,
        user: currentUser.name,
        act: "update",
        fieldsChanged: Object.keys(body).filter(key => body[key] !== undefined),
        oldValue: {
          content: existingTodo.content,
          tags: existingTodo.tags,
          assigned_to: existingTodo.assignedTo,
          status: existingTodo.status
        },
        newValue: {
          content: finalContent !== existingTodo.content ? finalContent : undefined,
          tags: tagsString !== existingTodo.tags ? tagsString : undefined,
          assigned_to: finalAssignedTo !== existingTodo.assignedTo ? finalAssignedTo : undefined,
          status: finalStatus !== existingTodo.status ? finalStatus : undefined
        },
        time: new Date().toISOString()
      },
      projectIdForAudit === null ? undefined : projectIdForAudit,
      todoIdNum
    ).catch(auditError => {
      console.error('创建TODO更新审计日志失败:', auditError);
    });

    return NextResponse.json(updatedTodoFull, { status: 200 });

  } catch (error: any) {
    console.error(`更新TODO任务 ${todoIdNum} 失败:`, error);
     if (error.message.includes('FOREIGN KEY constraint failed')) {
      return NextResponse.json({ message: '外键约束失败，请检查 assigned_to 是否有效' }, { status: 400 });
    }
    return NextResponse.json({ message: `服务器内部错误: ${error.message || '未知错误'}` }, { status: 500 });
  }
} 